package com.yndsoft.jc.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.R;
import com.yndsoft.jc.activity.BaseFragment;
import com.yndsoft.jc.model.Member;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.model.SupplierAdmin;
import com.yndsoft.jc.netutils.AppUtils;
import com.yndsoft.jc.supplier.main.SupplierActivity;
import com.yndsoft.jc.ui.memberpage.address.MailingAddressActivity;
import com.yndsoft.jc.ui.memberpage.login.ChooseRoleActivity;
import com.yndsoft.jc.ui.memberpage.login.LoginActivity;
import com.yndsoft.jc.ui.memberpage.myorder.MyOrderActivity;
import com.yndsoft.jc.ui.memberpage.personal.PersonalInfoActivity;
import com.yndsoft.jc.ui.memberpage.score.ScoreDetailActivity;
import com.yndsoft.jc.ui.memberpage.setting.SettingActivity;
import com.yndsoft.jc.ui.net.ApiService;
import com.yndsoft.jc.utils.CommMethodUtils;
import com.yndsoft.jc.utils.ConstantValues;
import com.yndsoft.jc.utils.DialogHelper;
import com.yndsoft.jc.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

//import com.facebook.drawee.view.SimpleDraweeView;

public class MemberFragment extends BaseFragment implements View.OnClickListener {
    private int mid = 0;
    private Member member;
    private Activity context;
    @Bind(R.id.fragment_member_layout_beibao)
    RelativeLayout fragment_member_layout_beibao;
    @Bind(R.id.fragment_member_layout_setting)
    RelativeLayout fragment_member_layout_setting;
    @Bind(R.id.fragment_member_layout_sendto)
    RelativeLayout fragment_member_layout_sendto;
    @Bind(R.id.fragment_member_layout_menpai)
    RelativeLayout fragment_member_layout_menpai;//个人资料
    @Bind(R.id.member_score)
    TextView member_score;
    public Dialog dialog;
    //别名（alias），设置标签（tag）
    //alias 应唯一， tag 即分组，没有唯一性
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

    @Bind(R.id.member_image)
    CircleImageView member_image;
    @Bind(R.id.login_regist)
    TextView login_regist;
    @Bind(R.id.tuijianma)
    TextView tuijianma;

    @Override
    public int getContentResouceId() {
        return R.layout.fragment_member;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        EventBus.getDefault().register(this);
        initView();
        initData();
        setListener();
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    private void setListener() {
        login_regist.setOnClickListener(this);
        fragment_member_layout_beibao.setOnClickListener(this);
        fragment_member_layout_setting.setOnClickListener(this);
        fragment_member_layout_sendto.setOnClickListener(this);
        fragment_member_layout_menpai.setOnClickListener(this);
        member_score.setOnClickListener(this);
    }

    private void initView() {
        dialog = DialogHelper.createLoadingDialog(context);
        int role = mSession.getRole();
        switch (role) {
            case 1:
                //会员
                member = mSession.getUserInfo();
                if (mSession.isLogin()) {
                    if (member != null) {
                        Glide.with(context).load(ApiService.BASE_URL + member.getImg()).placeholder(R.mipmap.default_head).into(member_image);
                        AppUtils.setText(login_regist, member.getPhone());
                        login_regist.setClickable(false);
                        login_regist.setText(member.getName() != null ? member.getName() : "");
                        tuijianma.setVisibility(View.VISIBLE);
                        AppUtils.setText(tuijianma, "推荐码：" + member.getCodeno());
                        AppUtils.setText(member_score, "积分:" + member.getPoint());
                    }
                } else {
                    member_image.setImageResource(R.mipmap.user_head_new);
                    login_regist.setText(R.string.login_register);
                    login_regist.setEnabled(true);
                    tuijianma.setVisibility(View.GONE);
                }
                break;
            case 2:
                //检测机构管理员
                SupplierAdmin supplierAdmin = mSession.getSuppilerAdmin();
                SupplierActivity.start(
                        getContext(),
                        supplierAdmin.getId() + "",
                        supplierAdmin.getTid(),
                        supplierAdmin.getSid() + "",
                        supplierAdmin.getName()
                );
                break;
            default:
                break;
        }

    }

    private void initData() {
        member = CommMethodUtils.getMember(context);
        if (CommMethodUtils.isLogin(context)) {
            //已登录
            setMember();
        } else {
            //未登录
            getMember();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
//            if (requestCode == ConstantValues.SETTING_REQUEST) {
//                initView();
//            } else if (requestCode == ConstantValues.LOGIN_REQUEST) {
//                initView();
//            }
            initView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public String getFragmentName() {
        return null;
    }

    @Subscribe
    public void onEventMainThread(String activityname) {
        if (activityname.equals("MemberStateUpdate")) {
            initData();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.login_regist:
                intent = new Intent(context, ChooseRoleActivity.class);
                startActivityForResult(intent, ConstantValues.LOGIN_REQUEST);
                break;
            case R.id.fragment_member_layout_beibao:
                if (mSession.isLogin()) {
                    intent = new Intent(context, MyOrderActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.fragment_member_layout_setting:
                intent = new Intent(context, SettingActivity.class);
                startActivityForResult(intent, ConstantValues.SETTING_REQUEST);
                break;
            case R.id.member_score:
//                SharedPreferences sp = context.getSharedPreferences(getString(R.string.sp_member), Context.MODE_PRIVATE);
//                String member = sp.getString(getString(R.string.sp_jc), "");
                if (mSession.isLogin()) {
                    intent = new Intent(context, ScoreDetailActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.fragment_member_layout_sendto:
                if (mSession.isLogin()) {
                    intent = new Intent(context, MailingAddressActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.fragment_member_layout_menpai:
                if (mSession.isLogin()) {
                    intent = new Intent(context, PersonalInfoActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.fragment_member_layout_member:
                    break;
                case R.id.fragment_member_layout_setting:
                    break;
                default:
                    break;
            }
        }
    }

    public void getMember() {
        if (member != null) {
            dialog.show();
            HashMap<String, String> params = new HashMap<>();
            params.put("type", "login");
            params.put("phone", member.getPhone());
            params.put("pwd", member.getPwd());
            String url_business = getString(R.string.url_business) + CommMethodUtils.getUrlParams(params);
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url_business)
                        .get()
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException ex) {
                        dialog.dismiss();
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        dialog.dismiss();
                        String data = response.body().string();
                        Type type = new TypeToken<ReturnMsg>() {
                        }.getType();
                        Object fromJson = new Gson().fromJson(data, type);
                        final ReturnMsg returnMsg = (ReturnMsg) fromJson;
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                switch (returnMsg.getCode()) {
                                    case 0:
                                        //Toast.makeText(context, "登录查询失败...", Toast.LENGTH_SHORT).show();
                                        login_error();
                                        break;
                                    case 1:
                                        //Toast.makeText(context, "登录成功......", Toast.LENGTH_SHORT).show();
                                        login_success(returnMsg.getInfo());
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                    }
                });
            } catch (Exception ex) {
                dialog.dismiss();
                Toast.makeText(context, "登录出错!", Toast.LENGTH_SHORT).show();
            }
        } else {

        }
    }

    public void login_success(String info) {
        Type m_type = new TypeToken<Member>() {
        }.getType();
        Object m_json = new Gson().fromJson(info, m_type);
        member = (Member) m_json;
        setMember();
        // 更新数据 start
        SharedPreferences sp = context.getSharedPreferences(getString(R.string.sp_member), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(getString(R.string.sp_jc), info);
        editor.commit();
        // 更新数据 end
        //极光推送
        //setTag(member.getPhone());
        //setAlias("f");
    }

    public void setMember() {
        if (member != null) {
            mid = member.getId();
        } else {
        }
    }

    public void login_error() {
        SharedPreferences sp = context.getSharedPreferences(getString(R.string.sp_member), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(getString(R.string.sp_jc));
        editor.clear();
        editor.commit();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                File file = new File("/data/data/" + context.getPackageName().toString() + "/shared_prefs", getString(R.string.sp_member) + ".xml");
                if (file.exists()) {
                    file.delete();
                }
            }
        }, 1500);
    }

    //-----------------------------JPush-----------------------------------

    /**
     * 设置tags
     */
    private void setTag(String tag) {
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
            Toast.makeText(context, "tag不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                Toast.makeText(context, "格式不对", Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }
        //Toast.makeText(MainActivity.this, "开始调用......", Toast.LENGTH_SHORT).show();
        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));
    }

    private void setAlias(String alias) {
        if (TextUtils.isEmpty(alias)) {
            Toast.makeText(context, "alias不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//            Toast.makeText(context, "格式不对", Toast.LENGTH_SHORT).show();
//            return;
//        }
        //调用JPush API设置Alias
        //mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, alias));
    }

    // 通过TagAliasCallback的接口回调来判断tag是否与极光推送服务器绑定成功
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            //Toast.makeText(MainActivity.this, "回调成功......", Toast.LENGTH_SHORT).show();
            final String logs;
            switch (code) {
                case 0:
                    logs = "设置别名和标签成功！";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "设置超时，60s后重试！";
                    // 延迟 60 秒来调用 Handler 设置别名
                    if (isConnected(context.getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Toast.makeText(context, "没有连接网络", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    logs = "失败代码 = " + code;
            }
            //ExampleUtil.showToast(logs, context.getApplicationContext());
        }
    };

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            JPushInterface.setAliasAndTags(context.getApplicationContext(), "xiaoyao", getSetString("s"), mTagsCallback);
//            switch (msg.what) {
//                case MSG_SET_ALIAS:
//                    Toast.makeText(MainActivity.this, "在handler里面设置alias", Toast.LENGTH_SHORT).show();
//                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mTagsCallback);
//                    break;
//                case MSG_SET_TAGS:
//                    Toast.makeText(MainActivity.this, "在handler里面设置tags", Toast.LENGTH_SHORT).show();
//                    try {
//                        JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
//                    } catch (Exception ex) {
//                        //Toast.makeText(MainActivity.this, "回调出错：" + ex.getMessage() , Toast.LENGTH_SHORT).show();
//                    }
//                    break;
//                default:
//                    break;
//            }
        }
    };

    // 校验Tag Alias 只能是数字,英文字母和中文
    public boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    public boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    public Set<String> getSetString(String tag) {
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                Toast.makeText(context, "格式不对", Toast.LENGTH_SHORT).show();
                return null;
            }
            tagSet.add(sTagItme);
        }
        return tagSet;
    }
}